package com.hnichr.ump.ping.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.hnichr.ump.common.ping.entity.SmsSendContent;
import com.hnichr.ump.common.ping.service.SmsSendContentService;
import com.hnichr.ump.common.ping.service.SmsSendService;
import com.hnichr.ump.common.ping.vo.SendResultVo;
import com.hnichr.ump.common.ping.vo.SmsSendVo;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.security.entity.Dict;
import com.mxpioframework.security.entity.DictItem;
import com.mxpioframework.security.util.SecurityUtils;
import com.mxpioframework.system.service.DictService;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.StringUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.util.*;

@Service
public class SmsSendServiceImpl implements SmsSendService {

    private static final Logger logger = LoggerFactory.getLogger(SmsSendServiceImpl.class);

    private static final String appKey = "HdWpnknJ";
    private static final String appSecret = "c899e8b72199324999e29e6dd91365534c12d9a4";

    private static final String url = "https://ping.hn-talent.com/send/v1/sendSms";

    @Autowired
    private DictService dictService;

    @Autowired
    private SmsSendContentService smsSendContentService;

    @Override
    public SendResultVo groupSend(SmsSendVo smsSendVo) {
        SendResultVo sendResultVo = send(smsSendVo);
        smsSendContentService.saveGroupSendResult(smsSendVo,sendResultVo);
        return sendResultVo;
    }

    @Override
    @Transactional
    public String sendFromImport(){
        String userName = SecurityUtils.getLoginUsername();
        List<SmsSendContent> smsSendContents = JpaUtil.linq(SmsSendContent.class).equal("status","-1").equal("createBy",userName).list();
        if(CollectionUtils.isEmpty(smsSendContents)){
            return "无可发送短信";
        }
        for(SmsSendContent content:smsSendContents ){
            SmsSendVo smsSendVo = new SmsSendVo();
            smsSendVo.setMobiles(content.getMobile());
            smsSendVo.setTitle("0");
            smsSendVo.setSmsContent(content.getContent());

            SendResultVo sendResultVo = send(smsSendVo);

            if(sendResultVo==null){
                content.setContent("0");
            }
            else if(sendResultVo.isSuccess()){
                content.setStatus("1");
            }
            else{
                content.setStatus("0");
            }
            content.setSendTime(new Date());
            JpaUtil.update(content);
        }
        return null;
    }

    private SendResultVo send(SmsSendVo smsSendVo) {
        TreeMap<String,String> treeMap = new TreeMap<>();
        treeMap.put("appKey",appKey);
        treeMap.put("mobiles",smsSendVo.getMobiles());
        treeMap.put("smsContent",smsSendVo.getSmsContent()+"【"+getTitle(smsSendVo.getTitle())+"】");
        treeMap.put("timestamp",String.valueOf(new Date().getTime()));
        treeMap.put("nonce", IdUtil.simpleUUID());
        treeMap.put("signatureMethod","HMAC-SHA1");
        String signature = getSignature(treeMap);
        treeMap.put("signature",signature);
        try{
            HttpResponse response = HttpUtil.createPost(url).contentType("application/json").body(JSON.toJSONString(treeMap)).execute();
            String responseBody = response.body();
            SendResultVo sendResultVo = JSON.parseObject(responseBody,SendResultVo.class);
            return sendResultVo;
        }
        catch (Exception e){
            logger.error(">>>>>>>>>>>短信发送异常",e);
            return null;
        }
    }

    public String getSignature(SortedMap<String,String> treeMap){
        List<String> valuesList = new ArrayList<>();
        for(Map.Entry<String,String> entry:treeMap.entrySet()){
            valuesList.add(entry.getValue());
        }
        String values = String.join("&",valuesList);
        try{
            String encodedValues = URLEncoder.encode(values,"UTF-8");
            Mac mac = Mac.getInstance("HmacSHA1");
            SecretKeySpec spec = new SecretKeySpec(appSecret.getBytes(), "HmacSHA1");
            mac.init(spec);
            byte[] byteHMAC = mac.doFinal(encodedValues.getBytes());
            org.apache.commons.codec.binary.Base64 base64 = new Base64();
            return base64.encodeAsString(byteHMAC);
        }
        catch (Exception e){
            return null;
        }
    }

    public String getTitle(String titleCode){
        Dict dict = dictService.getByCode("smsTitle");
        for(DictItem dictItem:dict.getItems()){
            if(StringUtils.equals(dictItem.getItemValue(),titleCode)){
                return dictItem.getItemText();
            }
        }
        return null;
    }
}
